<?php
/**                                          
 * 站点操作
 * @author M2
 * @version 1.0
 * create Date 2013-07-22
 */
class SiteAction extends PublicAction {
	/**
	 * 站点管理页面
	 * M2
	 */
	public function index() {
		$list = M('cms_site')->order('siteid')->select();
		$this->assign('list',$list);
		$this->display();
	}

    public function addsite() {
        $this->assign('ds', $this->getTemplateName(array('filename' => 'name')));
        $this->display();
    }
    private function getTemplateName($property) {
        $doc = new DOMDocument();
        import ( "ORG.Io.Dir" );
        $dirs = new Dir ('./Public/cms/template' );
        $arr = array();
        foreach ($dirs as $key => $value) {
            $dirss = new Dir($value['pathname']);
            foreach ($dirss as $keys => $values) {
                if ($values['filename'] == 'sitedata') {
                    $doc->load($values['pathname'].'/sitedata.xml'); //读取xml文件
                    $humans = $doc->getElementsByTagName( "sitetemplate" ); //取得sitetemplate标签的对象数组
                    foreach( $humans as $human ) {
                        $ds = array();
                        foreach ($property as $p => $pro) {
                            ${$pro} = $human->getElementsByTagName($pro);
                            ${$pro} = ${$pro}->item(0)->nodeValue;
                            if (in_array($p, array_keys($value))) {
                                $vs = $value[$p];
                                $ds[$vs] = ${$pro};
                            } else {
                                $ds[$p] = ${$pro};
                            }
                        }
                        $arr[] = $ds;
                    }
                }
            }
        }
        return $arr;
    }
	
	/**
	 * 添加站点
	 * M2
	 */
	public function doaddsite() {
        set_time_limit(0);
		if($_POST) {
            $selectTemplate = $_POST['selectTemplate'];
			$db = M('cms_site');
			$find = $db->where("status='1'")->getField('domain');
			$data['name'] = trim(strip_tags($_POST['name']));
			$data['dirname'] = trim(strip_tags($_POST['dirname']));
			$data['domain'] = empty($_POST['domain'])?$find.'/'.strip_tags($_POST['dirname']):$_POST['domain'];
			$data['site_title'] = strip_tags($_POST['site_title']);
			$data['keywords'] = strip_tags($_POST['keywords']);
			$data['description'] = strip_tags($_POST['description']);
			$data['site_type'] = $_POST['publish'];
			
			if(!empty($_POST['siteid'])) {
				$siteid = intval($_POST['siteid']);
				$find = D('Site')->checkSiteName($siteid,$data['name']);
				if($find) $this->error('站点名称已存在');
				if(false !== $db->where('siteid='.$siteid)->save($data)) {
                    S('cache_siteid_'.$siteid, null);
                    S('cache_siteconfig_'.$siteid, null);
					$this-> updSiteNode($data['name'],$siteid);
					$this->assign('jumpUrl',URL('cms/Site/index'));
					$this->success('修改成功');
				} else {
					$this->error('修改失败');
				}
			} else {
				$find = D('Site')->checkSiteName(0,$data['name']);
				if($find) $this->error('站点名称已存在');
				//添加站点数据
                if (empty($selectTemplate)) {
                    $map['plistid'] = '0';
                    $map['cname'] = '首页';
                    $map['catetemplate'] = 'channel.html';
                    $map['arttemplate'] = 'content.html';
                    $map['createurl'] = '';
                    $map['catenaming'] = 'channels-{cateid}.html';
                    $map['artnaming'] = 'contents-{contentid}.html';
                    $mid = $this->mid;
                    $map['create_uid'] = $mid;
                    $map['create_uname'] = common('String')->getUserName($mid);
                    $map['update_uid'] = $mid;
                    $map['update_uname'] = common('String')->getUserName($mid);
                    $map['inputtime'] = time();
                    $map['updatetime'] = time();
                    //添加栏目数据
                    if($cid = M('cms_category')->add($map)) {
                        unset($map);
                        //OOO  fix by jepin 20140915 将新增站点 排序改为1
                        //$map['display_order'] = $cid;
                        $map['display_order'] = 1;
                        $map['siteid'] = $cid;
                        //更新栏目的排序值
                        M('cms_category')->where('id='.$cid)->save($map);
                        //添加站点数据
                        $data['siteid'] = $cid;
                        if($id = $db->add($data)) {
                            $this->addSiteNode($data['name'],$id);
                            //添加模版数据
                            $arr[] = array('siteid'=>$id,'template_type'=>'home','template_name'=>'index.html','create_name'=>'index.html');
                            $arr[] = array('siteid'=>$id,'template_type'=>'channels','template_name'=>'channel.html','create_name'=>'');
                            $arr[] = array('siteid'=>$id,'template_type'=>'contents','template_name'=>'content.html','create_name'=>'');
                            M('cms_templates')->addAll($arr);
                            //获取站点目录
                            $path = D('Site')->getSiteInfo($id);
                            $path = $path.'templates/';
                            $arr = array('index.html','channel.html','content.html');
                            if (!file_exists($path)) {
                                mk_dir($path);
                            }
                            //创建空模版
                            foreach ($arr as $v) {
                                file_put_contents($path.$v,'');
                            }
                            $map['channelTemplate'] = 'channel.html';
                            $map['contentTemplate'] = 'content.html';
                            $map['catenaming'] = 'channels-{cateid}.html';
                            $map['artnaming'] = 'contents-{contentid}.html';
                            $map['picSavePath'] = './data/cms/upload';
                            $map['createchannel'] = '0';
                            $map['createcontent'] = '0';
                            $arr1['site-'.$id] = $map;
                            //添加配置信息
                            model('Data')->lput('cmsconfig', $arr1);
                        }
                        $this->assign('jumpUrl',URL('cms/Site/index'));
                        $this->success('添加成功');
                    } else {
                        $this->error('添加失败');
                    }
                } else {
                    if ($this->exportData($selectTemplate, $data)) {
                        $this->assign('jumpUrl',URL('cms/Site/index'));
                        $this->success('添加成功');
                    } else {
                        $this->error('添加失败');
                    }
                }
			}
		}
	}

    private function exportData($selectTemplate, $data) {
        $maxid = $this->readNodeXml('./Public/cms/template/'.$selectTemplate.'/sitedata/node.xml');
        if ($maxid) {
            $this->exportNodeData($maxid);
            $siteid = $this->readSiteXml('./Public/cms/template/'.$selectTemplate.'/sitedata/sitedata.xml', $maxid);
            $data['siteid'] = $siteid;
            M('cms_site')->add($data);
            $this->addSystemConfig('./Public/cms/template/'.$selectTemplate.'/sitedata/sitedata.xml', $siteid);
            $this->readTemplateXml('./Public/cms/template/'.$selectTemplate.'/sitedata/template.xml', $maxid);
            $this->readContentXml('./Public/cms/template/'.$selectTemplate.'/sitedata/content.xml', $maxid);
            $this->readGroupXml('./Public/cms/template/'.$selectTemplate.'/sitedata/group.xml', $maxid);
            $path = D('Site')->getSiteInfo($siteid);
            $templatePath = './Public/cms/template/'.$selectTemplate;
            $dir = opendir(SITE_PATH .'/'.$templatePath);
            @mkdir($path);
            while(false !== ( $file = readdir($dir)) ) {
                if (( $file != '.' ) && ( $file != '..' ) && ($file != 'sitedata')) {
                    if ( is_dir($templatePath . '/' . $file) ) {
                        recurse_copy($templatePath . '/' . $file,$path . '/' . $file);
                    } else {
                        copy($templatePath . '/' . $file,$path . '/' . $file);
                    }
                }
            }
            closedir($dir);
            return true;
        }
        return false;
    }
	
	/**
	 * 添加站点时，同时添加站点对应的节点
	 * @param unknown_type $sitename
	 */
	public function addSiteNode($sitename,$sid){
		$sitename = $sitename;
    	$sitenode = array('name'=>'cms','title'=>$sitename,'status'=>'1','remark'=>NULL,'sort'=>NULL,
				'pid'=>0,'level'=>1,'type'=>0,'group_id'=>0,'sid'=>$sid);
		$modulenodepid = M('node') -> add($sitenode);
		
		$modulenode = array('name'=>'Site','title'=>'站点管理','status'=>'1','remark'=>NULL,'sort'=>NULL,
				'pid'=>$modulenodepid,'level'=>2,'type'=>0,'group_id'=>0,'sid'=>$sid);
		$actionpids = M('node') -> add($modulenode);
		$actionnode[] = array('name'=>'index','title'=>'站点管理','status'=>'1','remark'=>NULL,'sort'=>NULL,
				'pid'=>$actionpids,'level'=>3,'type'=>0,'group_id'=>0,'sid'=>$sid);
		
		$modulenode = array('name'=>'Article','title'=>'内容管理','status'=>'1','remark'=>NULL,'sort'=>NULL,
				'pid'=>$modulenodepid,'level'=>2,'type'=>0,'group_id'=>0,'sid'=>$sid);
		$actionpids = M('node') -> add($modulenode);
		$actionnode[] = array('name'=>'contentlist','title'=>'内容列表','status'=>'1','remark'=>NULL,'sort'=>NULL,
				'pid'=>$actionpids,'level'=>3,'type'=>0,'group_id'=>0,'sid'=>$sid);
		$actionnode[] = array('name'=>'delArticle','title'=>'内容管理_删除','status'=>'1','remark'=>NULL,'sort'=>NULL,
				'pid'=>$actionpids,'level'=>3,'type'=>0,'group_id'=>0,'sid'=>$sid);
        $actionnode[] = array('name'=>'oper','title'=>'审核和生成','status'=>'1','remark'=>NULL,'sort'=>NULL,
                'pid'=>$actionpids,'level'=>3,'type'=>0,'group_id'=>0,'sid'=>$sid);
		
		$modulenode = array('name'=>'Cate','title'=>'栏目管理','status'=>'1','remark'=>NULL,'sort'=>NULL,
				'pid'=>$modulenodepid,'level'=>2,'type'=>0,'group_id'=>0,'sid'=>$sid);
		$actionpids = M('node') -> add($modulenode);
		$actionnode[] = array('name'=>'sitecatelist','title'=>'栏目管理','status'=>'1','remark'=>NULL,'sort'=>NULL,
				'pid'=>$actionpids,'level'=>3,'type'=>0,'group_id'=>0,'sid'=>$sid);
		$actionnode[] = array('name'=>'delCate','title'=>'栏目管理_删除','status'=>'1','remark'=>NULL,'sort'=>NULL,
				'pid'=>$actionpids,'level'=>3,'type'=>0,'group_id'=>0,'sid'=>$sid);
		
		$modulenode = array('name'=>'Template','title'=>'模板管理','status'=>'1','remark'=>NULL,'sort'=>NULL,
				'pid'=>$modulenodepid,'level'=>2,'type'=>0,'group_id'=>0,'sid'=>$sid);
		$actionpids = M('node') -> add($modulenode);
		$actionnode[] = array('name'=>'sitetemplatelist','title'=>'模板管理','status'=>'1','remark'=>NULL,'sort'=>NULL,
				'pid'=>$actionpids,'level'=>3,'type'=>0,'group_id'=>0,'sid'=>$sid);
		$actionnode[] = array('name'=>'deletetpl','title'=>'模板删除','status'=>'1','remark'=>NULL,'sort'=>NULL,
				'pid'=>$actionpids,'level'=>3,'type'=>0,'group_id'=>0,'sid'=>$sid);
		
		$modulenode = array('name'=>'Create','title'=>'生成管理','status'=>'1','remark'=>NULL,'sort'=>NULL,
				'pid'=>$modulenodepid,'level'=>2,'type'=>0,'group_id'=>0,'sid'=>$sid);
		$actionpids = M('node') -> add($modulenode);
		$actionnode[] = array('name'=>'create_home','title'=>'生成首页','status'=>'1','remark'=>NULL,'sort'=>NULL,
				'pid'=>$actionpids,'level'=>3,'type'=>0,'group_id'=>0,'sid'=>$sid);
		$actionnode[] = array('name'=>'create_cate','title'=>'生成栏目页','status'=>'1','remark'=>NULL,'sort'=>NULL,
				'pid'=>$actionpids,'level'=>3,'type'=>0,'group_id'=>0,'sid'=>$sid);
		$actionnode[] = array('name'=>'create_content','title'=>'生成内容页','status'=>'1','remark'=>NULL,'sort'=>NULL,
				'pid'=>$actionpids,'level'=>3,'type'=>0,'group_id'=>0,'sid'=>$sid);
		
		$modulenode = array('name'=>'Group','title'=>'分组管理','status'=>'1','remark'=>NULL,'sort'=>NULL,
				'pid'=>$modulenodepid,'level'=>2,'type'=>0,'group_id'=>0,'sid'=>$sid);
		$actionpids = M('node') -> add($modulenode);
		$actionnode[] = array('name'=>'sitegrouplist','title'=>'内容分组管理','status'=>'1','remark'=>NULL,'sort'=>NULL,
				'pid'=>$actionpids,'level'=>3,'type'=>0,'group_id'=>0,'sid'=>$sid);
		$actionnode[] = array('name'=>'sitegrouplist','title'=>'栏目分组管理','status'=>'1','remark'=>NULL,'sort'=>NULL,
				'pid'=>$actionpids,'level'=>3,'type'=>0,'group_id'=>0,'sid'=>$sid);
		
		$modulenode = array('name'=>'BlockClassify','title'=>'区块分类管理','status'=>'1','remark'=>NULL,'sort'=>NULL,
				'pid'=>$modulenodepid,'level'=>2,'type'=>0,'group_id'=>0,'sid'=>$sid);
		$actionpids = M('node') -> add($modulenode);
		$actionnode[] = array('name'=>'classify','title'=>'区块分类','status'=>'1','remark'=>NULL,'sort'=>NULL,
				'pid'=>$actionpids,'level'=>3,'type'=>0,'group_id'=>0,'sid'=>$sid);
		
		$modulenode = array('name'=>'Config','title'=>'配置管理','status'=>'1','remark'=>NULL,'sort'=>NULL,
				'pid'=>$modulenodepid,'level'=>2,'type'=>0,'group_id'=>0,'sid'=>$sid);
		$actionpids = M('node') -> add($modulenode);
		$actionnode[] = array('name'=>'siteconfiglist','title'=>'配置管理','status'=>'1','remark'=>NULL,'sort'=>NULL,
				'pid'=>$actionpids,'level'=>3,'type'=>0,'group_id'=>0,'sid'=>$sid);
		
		$modulenode = array('name'=>'Config','title'=>'云配置管理','status'=>'1','remark'=>NULL,'sort'=>NULL,
				'pid'=>$modulenodepid,'level'=>2,'type'=>0,'group_id'=>0,'sid'=>$sid);
		$actionpids = M('node') -> add($modulenode);
		$actionnode[] = array('name'=>'yunconfig','title'=>'又拍云配置','status'=>'1','remark'=>NULL,'sort'=>NULL,
				'pid'=>$actionpids,'level'=>3,'type'=>0,'group_id'=>0,'sid'=>$sid);
		
		$modulenode = array('name'=>'TextLink','title'=>'站内链接管理','status'=>'1','remark'=>NULL,'sort'=>NULL,
				'pid'=>$modulenodepid,'level'=>2,'type'=>0,'group_id'=>0,'sid'=>$sid);
		$actionpids = M('node') -> add($modulenode);
		$actionnode[] = array('name'=>'textLink','title'=>'站内链接管理','status'=>'1','remark'=>NULL,'sort'=>NULL,
				'pid'=>$actionpids,'level'=>3,'type'=>0,'group_id'=>0,'sid'=>$sid);
		$actionnode[] = array('name'=>'linkConfig','title'=>'站内链接配置','status'=>'1','remark'=>NULL,'sort'=>NULL,
				'pid'=>$actionpids,'level'=>3,'type'=>0,'group_id'=>0,'sid'=>$sid);
		$modulenode = array('name'=>'Article','title'=>'回收站管理','status'=>'1','remark'=>NULL,'sort'=>NULL,
				'pid'=>$modulenodepid,'level'=>2,'type'=>0,'group_id'=>0,'sid'=>$sid);
		$actionpids = M('node') -> add($modulenode);
		$actionnode[] = array('name'=>'deletecontentlist','title'=>'回收站','status'=>'1','remark'=>NULL,'sort'=>NULL,
				'pid'=>$actionpids,'level'=>3,'type'=>0,'group_id'=>0,'sid'=>$sid);
			
		M('node') -> addAll($actionnode);
	}
	
	/**
	 * 修改站点时，同时修改站点对应的节点
	 * @param unknown_type $sitename
	 */
	public function updSiteNode($sitename,$sid){
		M('node') -> where("`sid`={$sid} and level = 2") -> setField(array("name"=>$sitename,"title"=>$sitename));
		$nodes = M('node') -> where("`sid`={$sid} and level = 3") -> select();
		foreach ($nodes as $k => $v){
			$title = $v['title'];
			if(strpos($title,"_") !== false){
				$temp = explode("_",$title);
				$title = $sitename."_".$temp[1];
				$nodes[$k]["title"] = $title;
			}
			M('node') -> save($nodes[$k]);
		}
	}
	
	/**
	 * 删除站点时，同时删除站点对应的节点
	 * @param unknown_type $sitename
	 */
	public function delSiteNode($sid){
		$nodeIds = M('node') ->where("sid =".$sid)->field("id")->select();
		foreach ($nodeIds as $k => $v){
			$nodeIds[$k] = $nodeIds[$k]['id'];
		}
		$ids = implode(",",$nodeIds);
		M('node') ->where("sid =".$sid)->delete();
		M('access') ->where("`node_id` in(".$ids.")")->delete();
	}
	
	/**
	 * 修改站点
	 * M2
	 */
	public function editSite() {
		if(!empty($_GET['sid'])) {
			$sid = intval($_GET['sid']);
			$find = M('cms_site')->where('siteid='.$sid)->find();
            $this->assign('ds', $this->getTemplateName(array('filename' => 'name')));
			$this->assign($find);
			$this->display('addsite');
		} else {
			$this->error('获取站点信息失败');
		}
	}
	/**
	 * 删除站点
	 * M2
	 */
	public function delSite() {
		if(!empty($_GET['sid'])) {
			$data['siteid'] = intval($_GET['sid']);
            $dirname = M('cms_site')->where($data)->getField('dirname');
			$path = D('Site')->getSiteInfo($data['siteid']);
			if(M('cms_site')->where($data)->delete()) {
                S('cache_templatePath_'.$data['siteid'], null);
//                 if ($dirname) {
//                     if(file_exists($path)) {
//                         import('ORG.Io.Dir');
//                         Dir::delDir($path);
//                     }
//                 }
                M('system_data')->where(array('list' => 'cmsconfig', 'key' => 'site-'.$data['siteid']))->delete();
				M('cms_article')->where($data)->delete();
				M('cms_blockclassify')->where($data)->delete();
				M('cms_category')->where($data)->delete();
// 				M('cms_templates')->where($data)->delete();
				$this->delSiteNode($data['siteid']);
				$this->success('删除成功');
			} else {
				$this->error('删除失败');
			}
		} else {
			$this->error('获取站点信息失败');
		}
	}
	
	public function getSiteCateInfo() {
		$arr = array ();
		$list = M()->query("select id,cname,pid,content_num from ".$this->_dbPrefix."cms_category where pid<>0 union all select id,b.name,pid,content_num from ".$this->_dbPrefix."cms_category a,".$this->_dbPrefix."cms_site b where a.pid=0 
							and a.siteid=b.siteid order by id");
		foreach ($list as $k => $v) {
			$arr [] = array (
					'id' => $v['id'],
					'pId' => $v['pid'],
					'name' => $v ['cname']." (共".$v['content_num']."篇)",
					'open' => false,
					'checked' => true
			);
		}
		echo json_encode($arr);
	}

    /*
     * 导出模版
     * m2
     */
    public function doExportTemplate() {
        $sid = intval($_POST['siteid']);
        $dirname = $_POST['dirname'];
        $path = './Public/cms/template/'.$dirname;
        $xmlPath = $path.'/sitedata';
        $findSite = M('cms_site')->where('siteid='.$sid)->find();
        if (!file_exists($path)) {
            mk_dir($path);
        }
        // 导出栏目数据
        $cateList = M('cms_category')->where(array('siteid' => $sid))->order('id')->select();
        $this->writeXml($cateList, 'nodelist', $xmlPath.'/node.xml');

        // 导出分组数据
        $groupList = M('cms_group')->where(array('siteid' => $sid))->order('id')->select();
        $this->writeXml($groupList, 'grouplist', $xmlPath.'/group.xml');

        // 导出内容数据
        $contentList = M('cms_article')->where(array('siteid' => $sid))->order('id')->select();
        $this->writeXml($contentList, 'contentlist', $xmlPath.'/content.xml');

        // 导出模版数据
        $templateList = M('cms_templates')->where(array('siteid' => $sid))->order('id')->select();
        $this->writeXml($templateList, 'templatelist', $xmlPath.'/template.xml');

        // 过滤生成目录
        $distinctCatenaming = M('cms_category')->field('catenaming')->distinct(true)->where(array('siteid' => $sid))->select();
        $distinctArtnaming = M('cms_category')->field('artnaming')->distinct(true)->where(array('siteid' => $sid))->select();
        $changeStyle = model('Data')->get('cmsconfig:site-'.$sid);
        foreach ($distinctCatenaming as $dc) {
            if (strpos($dc['catenaming'], '/') !== false) {
                $explodeCate = explode('/', $dc['catenaming']);
                if (empty($explodeCate[0])) {
                    $dx[] = $explodeCate[1];
                } else {
                    $dx[] = $explodeCate[0];
                }
            } else {
                $explodeCate = explode('-', $dc['catenaming']);
                $dx[] = $explodeCate[0];
            }
        }

        foreach ($distinctArtnaming as $da) {
            if (strpos($da['artnaming'], '/') !== false) {
                $explodeCate = explode('/', $da['artnaming']);
                if (empty($explodeCate[0])) {
                    $dx[] = $explodeCate[1];
                } else {
                    $dx[] = $explodeCate[0];
                }
            } else {
                $explodeCate = explode('-', $da['artnaming']);
                $dx[] = $explodeCate[0];
            }
        }

        if (strpos($changeStyle['catenaming'], '/') !== false) {
            $explodeCate = explode('/', $changeStyle['catenaming']);
            if (empty($explodeCate[0])) {
                $dx[] = $explodeCate[1];
            } else {
                $dx[] = $explodeCate[0];
            }
        } else {
            $explodeCate = explode('-', $changeStyle['catenaming']);
            $dx[] = $explodeCate[0];
        }

        if (strpos($changeStyle['artnaming'], '/') !== false) {
            $explodeCate = explode('/', $changeStyle['artnaming']);
            if (empty($explodeCate[0])) {
                $dx[] = $explodeCate[1];
            } else {
                $dx[] = $explodeCate[0];
            }
        } else {
            $explodeCate = explode('-', $changeStyle['artnaming']);
            $dx[] = $explodeCate[0];
        }

        foreach ($templateList as $k => $v) {
            if (!empty($v['create_name'])) {
                $dx[] = $v['create_name'];
            }
        }
        $dir = opendir(SITE_PATH .'/'.$findSite['dirname']);
        @mkdir($path);
        while(false !== ( $file = readdir($dir)) ) {
            if (( $file != '.' ) && ( $file != '..' ) && !(in_array($file, array_unique($dx)))) {
                if ( is_dir($findSite['dirname'] . '/' . $file) ) {
                    recurse_copy($findSite['dirname'] . '/' . $file,$path . '/' . $file);
                } else {
                    copy($findSite['dirname'] . '/' . $file,$path . '/' . $file);
                }
            }
        }
        closedir($dir);

        // 创建站点数据
        unset($_POST['__hash__']);
        unset($_POST['siteid']);
        $arr = array();
        $arr[] = $_POST;
        $this->writeXml($arr, 'sitetemplate', $xmlPath.'/sitedata.xml', array(array('config' => $findSite, 'elementName' => 'siteconfig'),array('config' => $changeStyle, 'elementName' => 'siteOutherConfig')));
        $this->success('导出成功', URL('cms/Site'));
    }

    public function uploadPic() {
        $dirname = $_GET['dirname'];
        uploadPic('./Public/cms/template/'.$dirname.'/sitedata', 'Public/cms/template/'.$dirname.'/sitedata', null, false);
    }

    /*
     * 展示门户风格
     * m2
     */
    public function style() {
        $ds = $this->getTemplateName(array('name' => 'name', 'dir' => 'dirname', 'pic' => 'templatePic'));
        $this->assign('ds', $ds);
        $this->display();
    }

    private function writeXml($arr = array(), $elementName, $filename, $nextElement) {
        $doc = new DOMDocument('1.0', 'utf-8');
        $doc->formatOutput = true;
        $r = $doc->createElement("feed");
        $doc->appendChild($r);
        foreach ($arr as $k => $v) {
            $list = $doc->createElement($elementName);
            $key = array_keys($v);
            foreach ($key as $kk) {
                $name = $doc->createElement($kk);
                $name->appendChild($doc->createCDATASection($v[$kk]));
                $list->appendChild($name);
            }
            $r->appendChild($list);
        }

        if (!empty($nextElement)) {
            foreach ($nextElement as $k => $v) {
                $nextList = $doc->createElement($v['elementName']);
                foreach ($v['config'] as $k => $v) {
                    $name = $doc->createElement($k);
                    $name->appendChild($doc->createCDATASection($v));
                    $nextList->appendChild($name);
                }
                $r->appendChild($nextList);
            }
        }
        $doc->save($filename);
    }

    /*
     * 读取栏目的xml数据
     * M2
     */
    private function readNodeXml($path) {
        $dropResult = M()->query('DROP TABLE IF EXISTS '.$this->_dbPrefix.'tmp_category');
        if ($dropResult !== false) {
            $createResult = M()->query('CREATE TABLE `'.$this->_dbPrefix.'tmp_category` select * from '.$this->_dbPrefix.'cms_category where 1=2');
            if ($createResult !== false) {
                $doc = new DOMDocument();
                $doc->load($path);
                $nodeList = $doc->getElementsByTagName( "nodelist" );
                foreach( $nodeList as $node ) {
                    $headline = array();
                    if ($node->childNodes->length) {
                        foreach ($node->childNodes as $i) {
                            $headline[$i->nodeName] = $i->nodeValue;
                        }
                    }
                    M('tmp_category')->add($headline);
                }
                $maxid = M('cms_category')->max('id');
                return $maxid;
            }
        }
        return null;
    }

    /*
     * 导入栏目数据
     * M2
     */
    private function exportNodeData($maxid) {
        $tmpCategoryList = M('tmp_category')->select();
        foreach ($tmpCategoryList as $k => $v) {
            if (!empty($v['plistid'])) {
                if (strpos($v['plistid'], ',')) {
                    $explodePlist = explode(',', $v['plistid']);
                    for ($i = 0; $i < count($explodePlist); $i++) {
                        if (!empty($explodePlist[$i])) {
                            $explodePlist[$i] += $maxid;
                        }
                    }
                    $implodeList = implode(',', $explodePlist);
                } elseif (strpos($v['plistid'], '-')) {
                    $explodePlist = explode('-', $v['plistid']);
                    for ($i = 0; $i < count($explodePlist); $i++) {
                        if (!empty($explodePlist[$i])) {
                            $explodePlist[$i] += $maxid;
                        }
                    }
                    $implodeList = implode('-', $v['plistid']);
                } elseif ($v['plistid'] > 0) {
                    $implodeList = $v['plistid'] + $maxid;
                } else {
                    $implodeList = $v['plistid'];
                }
            } else {
                $implodeList = $v['plistid'];
            }
            $data['id'] = $v['id'] + $maxid;
            $data['siteid'] = $v['siteid'] + $maxid;
            if ($v['pid'] > 0) {
                $data['pid'] = $v['pid'] + $maxid;
            } else {
                $data['pid'] = $v['pid'];
            }
            $data['plistid'] = $implodeList;
            M('tmp_category')->where('id='.$v['id'])->save($data);
        }
        M()->query('insert into '.$this->_dbPrefix.'cms_category select * from '.$this->_dbPrefix.'tmp_category');
        M()->query('drop table '.$this->_dbPrefix.'tmp_category');
    }

    /*
     * 读取站点的xml数据并且导入站点数据
     * M2
     */
    private function readSiteXml($path, $maxid) {
        $doc = new DOMDocument();
        $doc->load($path);
        $nodeList = $doc->getElementsByTagName( "siteconfig" );
        $siteid = 0;
        foreach( $nodeList as $node ) {
            $headline = array();
            if ($node->childNodes->length) {
                foreach ($node->childNodes as $i) {
                    $headline[$i->nodeName] = $i->nodeValue;
                }
            }
            $siteid = $headline['siteid'] + $maxid;
        }
        return $siteid;
    }

    /*
     * 读取站点其他配置
     */
    private function addSystemConfig($path, $sid) {
        $doc = new DOMDocument();
        $doc->load($path);
        $nodeList = $doc->getElementsByTagName( "siteOutherConfig" );
        foreach( $nodeList as $node ) {
            $headline = array();
            if ($node->childNodes->length) {
                foreach ($node->childNodes as $i) {
                    $headline[$i->nodeName] = $i->nodeValue;
                }
            }
            unset($headline['#text']);
            $arr['site-'.$sid] = $headline;
            model('Data')->lput('cmsconfig', $arr);
        }
    }

    /*
     * 读取模版的xml数据并且导入模版数据
     * M2
     */
    private function readTemplateXml($path, $maxid) {
        $doc = new DOMDocument();
        $doc->load($path);
        $nodeList = $doc->getElementsByTagName( "templatelist" );
        $maxTemplateId = M('cms_templates')->max('id');
        foreach( $nodeList as $node ) {
            $headline = array();
            if ($node->childNodes->length) {
                foreach ($node->childNodes as $i) {
                    $headline[$i->nodeName] = $i->nodeValue;
                }
            }
            $headline['id'] = ++$maxTemplateId;
            $headline['siteid'] = $headline['siteid'] + $maxid;
            M('cms_templates')->add($headline);
        }
    }

    /*
     * 读取模版的xml数据并且导入模版数据
     * M2
     */
    private function readContentXml($path, $maxid) {
        $doc = new DOMDocument();
        $doc->load($path);
        $nodeList = $doc->getElementsByTagName( "contentlist" );
        $maxContentId = M('cms_article')->max('id');
        foreach( $nodeList as $node ) {
            $headline = array();
            if ($node->childNodes->length) {
                foreach ($node->childNodes as $i) {
                    $headline[$i->nodeName] = $i->nodeValue;
                }
            }
            $headline['id'] = ++$maxContentId;
            $headline['siteid'] = $headline['siteid'] + $maxid;
            $headline['cid'] = $headline['cid'] + $maxid;
            M('cms_article')->add($headline);
        }
    }

    /*
     * 读取分组的xml数据并且导入分组数据
     * M2
     */
    private function readGroupXml($path, $maxid) {
        $doc = new DOMDocument();
        $doc->load($path);
        $nodeList = $doc->getElementsByTagName( "grouplist" );
        $maxGroupId = M('cms_group')->max('id');
        foreach( $nodeList as $node ) {
            $headline = array();
            if ($node->childNodes->length) {
                foreach ($node->childNodes as $i) {
                    $headline[$i->nodeName] = $i->nodeValue;
                }
            }
            $headline['id'] = ++$maxGroupId;
            $headline['siteid'] = $headline['siteid'] + $maxid;
            M('cms_group')->add($headline);
        }
    }
}
?>
